// <!--
//  * 严肃声明：
//  * 开源版本请务必保留此注释头信息，若删除我方将保留所有法律责任追究！
//  * 可正常分享和学习源码，不得用于违法犯罪活动，违者必究！
//  * Copyright (c) 2022 APThink David唐 all rights reserved.
//  * 版权所有，侵权必究！
//  *
// -->
import axios from "axios";
import { ElLoading } from "element-plus";
import router from "@/router";
import { errorMessage, toast, storage, getToken, removeToken } from "@/utils";
import { ApiUrl } from "@/contants";
// import store from "@/store";
import { i18n } from "@/i18n";
import { ResponseEnum } from './ResponseEnum'

//创建axios的一个实例
const instance = axios;

let loading: any;
//正在请求的数量
let requestCount = 0;

//显示loading
const showLoading = () => {
  !requestCount &&
    (loading = ElLoading.service({
      lock: true,
      text: i18n.global.t("message.loading"),
      background: "rgba(0, 0, 0, 0.7)",
    }));
  requestCount++;
};

//隐藏loading
const hideLoading = () => {
  requestCount--;
  requestCount || loading.close();
};

// baseURL: import.meta.env.VITE_BASE_API_URL, //接口统一域名
instance.defaults.baseURL = ApiUrl; //接口统一域名
instance.defaults.timeout = 60000; //设置请求超时60s
instance.defaults.headers["Content-Type"] = "application/json;charset=UTF-8;";

//请求拦截器
instance.interceptors.request.use(
  (config) => {
    // showLoading();
    // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
    const token = getToken();
    token && (config.headers["ApthinkToken"] = token);
    // //若请求方式为post，则将data参数转为JSON字符串
    // if (config.method.toUpperCase === 'POST') {
    //     config.data = JSON.stringify(config.data);
    // }
    config.headers["AcceptLanguage"] = storage.get("ApthinkLanguage") || "zh";
    return Promise.resolve(config);
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

//响应拦截器
instance.interceptors.response.use(
  (response) => {
    // hideLoading()
    const data = response.data
    const id = data.errorid
    if (id != ResponseEnum.Ok) {
      //非法系统签名或者系统授权日期已截止
      if (id == ResponseEnum.ErrorInvalidSign) {
        router.replace({
          path: "/about",
          query: { redirect: router.currentRoute.value.fullPath }, //登录成功后跳入浏览的当前页面
        });
      }
      //未登录或者已登陆用户会话已过期或者已登录用户访问权限异常
      if (id == ResponseEnum.ErrorNoLogin || id == ResponseEnum.ErrorNoPermission) {
        removeToken();
        router.replace({
          path: "/login",
          query: { redirect: router.currentRoute.value.fullPath }, //登录成功后跳入浏览的当前页面
        })
      }
      errorMessage(data)
      return Promise.reject();
    } else {
      //响应成功
      return Promise.resolve(data)
    }
  },
  (error) => {
    hideLoading();
    // console.log("拦截器报错", error);
    //响应错误
    if (error && error.response) {
      const status = error.response.status;
      let message;
      switch (status) {
        case 400:
          message = "请求错误";
          break;
        case 401:
          message = "请求错误";
          break;
        case 404:
          message = "请求地址出错";
          break;
        case 408:
          message = "请求超时";
          break;
        case 500:
          message = "服务器内部错误!";
          break;
        case 501:
          message = "服务未实现!";
          break;
        case 502:
          message = "网关错误!";
          break;
        case 503:
          message = "服务不可用!";
          break;
        case 504:
          message = "网关超时!";
          break;
        case 505:
          message = "HTTP版本不受支持";
          break;
        default:
          message = error.message;
      }
      toast(message, "error");
    }
    return Promise.reject(error);
  }
);

export default instance;
